package com.glacier.cloud.order.controller;

import com.glacier.cloud.order.consts.Constant;
import com.glacier.cloud.order.entity.dto.cmd.OrderCreatCmd;
import com.glacier.cloud.order.entity.event.OrderCreateEvent;
import com.glacier.cloud.order.entity.event.ProductEvent;
import com.glacier.cloud.order.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * date 2023-12-04 10:35
 *
 * @author glacier
 * @version 1.0
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;
    @Resource
    private StreamBridge streamBridge;

    @PostMapping("/create")
    public int createOrder(@RequestBody OrderCreatCmd command) {
        return orderService.createOrder(command);
    }


    @PostMapping("/send1")
    public String send1(@RequestBody OrderCreatCmd command) {
        streamBridge.send(Constant.DEMO_OUT, command);
        return "success";
    }

    @GetMapping("/send2")
    public String send2() {
        String sn = UUID.randomUUID().toString().replaceAll("-", "");
        // 发送消息
        Message<String> message = MessageBuilder.withPayload(sn)
                .setHeader("x-delay", 10 * 1000)
                .build();

        streamBridge.send(Constant.DEMO1_OUT, message);
        return sn;
    }

    @PostMapping("/send3")
    public String send3(@RequestBody OrderCreatCmd command) {
        Long orderId = 1L;
        List<ProductEvent> productEvents = command.getProducts()
                .stream()
                .map(e -> new ProductEvent(e.getProductSkuId(), e.getQuantity()))
                .collect(Collectors.toList());
        streamBridge.send(Constant.ORDER_OUT, new OrderCreateEvent(orderId, command.getCustomerUserId(), productEvents));
        return "success";
    }

    @GetMapping("/send4")
    public String send4() {
        String sn = UUID.randomUUID().toString().replaceAll("-", "");
        // 发送消息
        Message<String> message = MessageBuilder.withPayload(sn)
                .setHeader("x-delay", 10 * 1000)
                .build();

        streamBridge.send(Constant.ORDER1_OUT, message);
        return sn;
    }
}
